package com.hcc.gateway.app.filter;

import cn.hutool.core.util.StrUtil;
import com.hcc.gateway.app.config.HccGatewayConfig;
import com.hcc.gateway.common.utils.JsonUtils;
import com.hcc.gateway.netty.context.GatewayExchange;
import com.hcc.gateway.netty.context.ReqContext;
import com.hcc.gateway.netty.context.RespContext;
import com.hcc.gateway.netty.filter.GatewayFilterChain;
import com.hcc.gateway.netty.support.ByteBufUtils;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpResponseStatus;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * AppUriPrefixFilter
 *
 * @author shengjun.hu
 * @date 2021/12/27
 */
@Slf4j
@Component
public class UriPrefixFilter extends AbstractGatewayFilter {

    @Autowired
    private HccGatewayConfig config;

    public String getProxyPrefix() {
        return config.getProxyPrefix();
    }

    @Override
    public int getOrder() {
        return 50;
    }

    @Override
    public void filter(GatewayExchange exchange, GatewayFilterChain chain) {
        log.info("进入AppUriPrefixFilter !");
        String proxyPrefix = this.getProxyPrefix();
        if (StrUtil.isEmpty(proxyPrefix)) {
            chain.filter(exchange);
            return;
        }
        String uri = exchange.getReqContext().getUri();
        if (!uri.startsWith(proxyPrefix)) {
            this.writeResponse(exchange);
            return;
        }
        chain.filter(exchange);
    }

    @Override
    protected void writeResponse(GatewayExchange exchange) {
        ReqContext reqContext = exchange.getReqContext();
        RespContext respContext = exchange.getRespContext();

        String msg = String.format("URI: [%s]不被支持！尝试添加前缀：[%s]}", reqContext.getUri(), config.getProxyPrefix());
        respContext.setHttpStatus(HttpResponseStatus.NOT_FOUND);
        respContext.getHeaders().set(HttpHeaderNames.CONTENT_TYPE, "application/json;charset=UTF-8");

        Map<String, String> resultMap = new HashMap<>();
        resultMap.put("errorMsg", msg);

        respContext.setBody(ByteBufUtils.writeStringToByteBuf(JsonUtils.writeValueAsString(resultMap)));
    }

}
